package com.siecom.transport.handler;

import android.util.Log;

import com.siecom.constconfig.ConstDefine;
import com.siecom.proto.Message;
import com.siecom.transport.CommServer;
import com.siecom.transport.ConnectStatusCallback;
import com.siecom.transport.SiecomDevice;
import com.siecom.transport.bluetooth.BlueServer;

import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by zhq on 2017/2/4.
 */

public class HeartbeatHandler implements ServiceHandler {

    private volatile int timesCount = 0;
    private ConnectStatusCallback callback = null;
    public void setConnectStatusCallback(ConnectStatusCallback callback){
        this.callback = callback;
    }
    private static Timer timer = null;

    public void cancelHeartbeat(){

        if(timer!=null){
            timer.cancel();
            timer =null;
        }
    }
    public void startHeartbeat(int intervalMs){
        TimerTask task = new TimerTask() {
            @Override
            public void run() {
                // task to run goes here

                if(timesCount>2){
                    Log.e("HeartbeatHandler","timeOut!");
                    if(callback!=null)
                    callback.onDisConnect(new Exception("Heartbeat timout"));
                    timesCount = 0;
                }
                timesCount++;
            }
        };
        cancelHeartbeat();
        long delay = 0;
        long intevalPeriod = intervalMs;
        timer = new Timer();
        // schedules the task to be run in an interval
        timer.scheduleAtFixedRate(task, delay, intevalPeriod);
    }

    @Override
    public void onReceive(CommServer server, Message.siecomproto msg,String message) {

        timesCount--;

    }
}
